from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from app01.forms.account import RegisterModelForm, SendMessageForm, LoginForm


# Create your views here.

@csrf_exempt
def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, './app01/register.html', {'form': form})
    print(request.POST)
    form = RegisterModelForm(request.POST)
    if form.is_valid():
        # save的方式会自动剔除数据库中不存在的字段
        # 如果手动创建需要先手动剔除不用的字段
        form.save()
        print('成功了')
        return JsonResponse({'status': True, 'redirect_url': '/app01/login/'})
    print(form.errors)
    return JsonResponse({'status': False, 'error': form.errors})


def get_code(request):
    '''验证码以图片形式返回时可以用HttpResponse(ByteIO)形式返回给url'''
    if request.method == 'GET':
        print(request.GET)
        form = SendMessageForm(request.GET)
        if form.is_valid():
            return JsonResponse({'status': True})

        return JsonResponse({'status': False, 'error': form.errors})


def index(request):
    return render(request, 'app01/index.html')


def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'app01/login.html', {'form': form})

    form = LoginForm(request.POST)
    if form.is_valid():

        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        print(username, password)

        user_obj = models.UserInfo.objects.filter(Q(username=username) | Q(email=username)).filter(
            password=password).first()
        if user_obj:
            # 修改session的过期时间
            request.session.set_expiry(60 * 60 * 24 * 14)
            request.session['user_id'] = user_obj.id
            request.session['user_name'] = user_obj.username
            return redirect('app01:index')
        form.add_error('password', '密码错误')

    return render(request, 'app01/login.html', {'form': form})


def home(request):
    return render(request, 'app01/home.html')


def logout(request):
    request.session.flush()
    print('name')
    return redirect('app01:index')
